<template>
  <div class="page-wrap">
    <a-card title="菜单管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-input v-model="keyword" placeholder="菜单名关键词" allow-clear style="width: 200px" />
          <a-button type="primary" @click="filterTree">查询</a-button>
          <a-button @click="resetFilter">重置</a-button>
          <a-button type="primary" status="success" @click="openEdit()">新增</a-button>
        </a-space>
      </template>

      <!-- 使用树形表格代替左右分栏布局 -->
      <a-table
          :data="treeTableData"
          :columns="columns"
          row-key="menuId"
          :tree-row-key="'menuId'"
          :children-key="'children'"
          :default-expanded-all="false"
          :pagination="false"
      />
    </a-card>

    <a-modal v-model:visible="editVisible" :title="editing?.menuId ? '编辑菜单' : '新增菜单'" :mask-closable="false" @ok="saveMenu" :confirm-loading="saving" :width="640">
      <a-form :model="editing" layout="vertical">
        <a-form-item field="parentId" label="上级菜单">
          <a-tree-select
              v-model="editing.parentId"
              :data="rawTree"
              :field-names="{ key: 'menuId', title: 'menuName', children: 'children' }"
              allow-clear
              placeholder="选择上级菜单"
          />
        </a-form-item>
        <a-form-item field="menuName" label="菜单名称" :rules="[{ required: true, message: '请输入菜单名称' }]">
          <a-input v-model="editing.menuName" />
        </a-form-item>
        <a-form-item field="path" label="路由路径">
          <a-input v-model="editing.path" />
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="(editing as any).sort" :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { SysMenu } from '@/types/system';
import { menuList, menuAdd, menuUpdate, menuDelete } from '@/api/menu';

const rawTree = ref<SysMenu[]>([]);
const treeTableData = ref<SysMenu[]>([]);
const keyword = ref('');

// 表格列配置
const columns = computed(() => [
  {
    title: 'ID',
    dataIndex: 'menuId',
    width: 100,
  },
  {
    title: '名称',
    dataIndex: 'menuName',
  },
  {
    title: '路径',
    dataIndex: 'path',
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 100,
  },
  {
    title: '操作',
    width: 220,
    // render: (_, record: SysMenu) => (
    // <a-space>
    //   <a-button type="text" onClick={() => openEdit(record)}>编辑</a-button>
    //   <a-popconfirm content="确认删除该菜单？" onOk={() => onDelete(record)}>
    //     <a-button type="text" status="danger">删除</a-button>
    //   </a-popconfirm>
    // </a-space>
    // )
  },
]);

function buildFlatList(nodes: SysMenu[], pid?: number, list: SysMenu[] = []) {
  for (const n of nodes) {
    (n as any)._pid = pid;
    list.push(n);
    if (n.children && n.children.length) {
      buildFlatList(n.children, n.menuId, list);
    }
  }
  return list;
}

// 过滤树形表格数据
function filterTree() {
  if (!keyword.value) {
    treeTableData.value = JSON.parse(JSON.stringify(rawTree.value));
    return;
  }

  const list = buildFlatList(rawTree.value);
  const ids = new Set(list.filter(x => (x.menuName || '').includes(keyword.value)).map(x => x.menuId));
  const clone = JSON.parse(JSON.stringify(rawTree.value));

  function dfs(nodes: any[]): any[] {
    return nodes
        .map(n => ({ ...n, children: n.children ? dfs(n.children) : [] }))
        .filter(n => ids.has(n.menuId) || (n.children && n.children.length));
  }

  treeTableData.value = dfs(clone);
}

function resetFilter() {
  keyword.value = '';
  treeTableData.value = JSON.parse(JSON.stringify(rawTree.value));
}

const editVisible = ref(false);
const saving = ref(false);
const editing = reactive<Partial<SysMenu & { sort?: number }>>({});

function openEdit(row?: SysMenu) {
  editVisible.value = true;
  Object.assign(editing, { menuId: undefined, parentId: undefined, menuName: '', path: '', sort: 0 });
  if (row?.menuId) Object.assign(editing, row);
}

async function saveMenu() {
  saving.value = true;
  try {
    if ((editing as any).menuId) {
      await menuUpdate(editing as any);
      Message.success('已保存');
    } else {
      await menuAdd(editing as any);
      Message.success('已新增');
    }
    editVisible.value = false;
    await loadTree();
  } finally {
    saving.value = false;
  }
}

async function onDelete(row: SysMenu) {
  await menuDelete([row.menuId]);
  Message.success('已删除');
  await loadTree();
}

async function loadTree() {
  const res = await menuList();
  rawTree.value = res.data || [];
  treeTableData.value = JSON.parse(JSON.stringify(rawTree.value));
}

onMounted(loadTree);
</script>

<style scoped>
.page-wrap { padding: 12px; }
</style>
